package com.myhome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myhome.entity.Admin;
import com.myhome.entity.Menu;
import com.myhome.entity.RespBean;
import com.myhome.mapper.AdminMapper;
import com.myhome.mapper.MenuMapper;
import com.myhome.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myhome.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-09-04
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder encoder;
    @Autowired
    SecurityUtils securityUtils;
    @Value("${jwt.tokenHead}")
    String tokenHeader;
    @Autowired
    MenuMapper menuMapper;
    @Override
    public RespBean login(String username, String password, String captcha, HttpServletRequest request) {
        String code = (String) request.getSession().getAttribute("captcha");
        System.out.println("c="+captcha);
        if (StringUtils.isEmpty(captcha) || !code.equalsIgnoreCase(captcha)) {
            return RespBean.error("验证码错误，请重新输入");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !encoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或者密码错误");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("该账号被禁用，请联系管理员");
        }
        Object userDetails1;
        Object principal;
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        HashMap<String, String> result = new HashMap<>();
        String token = securityUtils.generateToken(userDetails);
        String header = this.tokenHeader;
        result.put("token", token);
        result.put("header",header);
        return RespBean.success("登陆成功",result);
    }

    @Override
    public Admin getUserInfo(String name) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("username",name);
        wrapper.eq("enabled",true);
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",name).eq("enabled",true));
    }

    @Override
    public List<Menu> getMenuByUserId() {
        return menuMapper.getMenuByUserId(((Admin)(SecurityContextHolder.getContext().getAuthentication().getPrincipal())).getId());
    }

    @Override
    public List<Admin> getSearchToAdmin(String keywords) {
        Integer id = ((Admin) (SecurityContextHolder.getContext().getAuthentication().getPrincipal())).getId();
        return adminMapper.getSearchToAdmin(id,keywords);
    }

    @Override
    public RespBean updateAdminPassword(Map<String, Object> password, Authentication authentication) {
        String oldPassword = (String) password.get("oldPassword");
        String newPassword = (String) password.get("newPassword");
        System.out.println("auth:  "+authentication);
        Admin admin = (Admin) authentication.getPrincipal();
        Admin user = adminMapper.selectById(admin.getId());
        System.out.println("true?:  "+encoder.matches(oldPassword, user.getPassword()));
        if (encoder.matches(oldPassword,user.getPassword()) ) {
            int count = adminMapper.updateById(user.setPassword(encoder.encode(newPassword)));
            System.out.println(count);
            if (1 == count) {
                return RespBean.success("修改成功");
                //SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken());
            }
            return RespBean.error("修改失败");
        }
        return RespBean.error("旧密码不正确,修改失败");
    }
}
